package org.psyduck.admin.user.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.psyduck.admin.menu.service.MenuService;
import org.psyduck.admin.user.service.UserService;
import org.psyduck.common.model.PageJsonBean;
import org.psyduck.common.utils.WebUtils;
import org.psyduck.security.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    MenuService menuService;

    @RequestMapping("list")
    public PageJsonBean list(Page page, User user){
        return PageJsonBean.success(userService.getDao().selectPage(page,user));
    }

    @PreAuthorize("hasAuthority('user:save')")
    @RequestMapping("save")
    public boolean save(User user, String roles){
        return userService.save(user, roles);
    }

    @PreAuthorize("hasAuthority('user:delete')")
    @RequestMapping("delete")
    public boolean delete(String... id){
        if(id.length > 1){
            return userService.removeByIds(Arrays.asList(id));
        }
        return userService.delete(id[0]);
    }

    @RequestMapping("info")
    public User info(){
        User user = userService.getById(WebUtils.getUserId());
        user.setAuthorities(userService.getCurrentUserAuthorities(user.getId()));
        return user;
    }

    @RequestMapping("detail")
    public User detail(String id){
        User user = userService.getById(id);
        user.setRoles(userService.getDao().getUserRoles(user.getId()));
        return user;
    }

    @RequestMapping("getUserRoles")
    public List<String> getUserRoles(String userId){
        return userService.getDao().getUserRoles(userId);
    }

    @RequestMapping("changeIsLogin")
    public boolean changeIsLogin(User user){
        return userService.updateById(user);
    }

}